package com.teziyou.commodity.web.jfinal;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSON;
import com.jfinal.core.Controller;
import com.teziyou.commodity.util.SqlUtil;

/**
 * 控制器基类
 * @author kangrui
 *
 */
@SuppressWarnings({"rawtypes", "unchecked"})
public class BaseController extends Controller {
	
	/**
	 * 返回成功
	 * @param msg
	 * @return
	 */
	protected String success(String msg, Object obj) {
		Map result = new HashMap();
		result.put("isSuccess", true);
		result.put("msg", msg);
		result.put("obj", obj);
		return JSON.toJSONString(result);
	}
	
	/**
	 * 返回成功
	 * @param msg
	 * @return
	 */
	protected String fail(String msg, Object obj) {
		Map result = new HashMap();
		result.put("isSuccess", false);
		result.put("msg", msg);
		result.put("obj", obj);
		return JSON.toJSONString(result);
	}
	
	/**
	 * 返回失败
	 * @param msg
	 * @return
	 */
	protected String fail(String msg) {
		return fail(msg, null);
	}
	
	/**
	 * 返回成功
	 * @param msg
	 * @return
	 */
	protected String success(String msg) {
		return success(msg, null);
	}
	
	protected String success() {
		return success(null, null);
	}
	
	protected String fail() {
		return fail(null, null);
	}
	
	public Map<String, String> getParamMap() {
		Map<String, String[]> map = getParaMap();
		Map<String, String> newmap = new HashMap<>();
		for(Map.Entry<String, String[]> entry:map.entrySet()) {
			newmap.put(entry.getKey(), StringUtils.join(entry.getValue(), ","));
		}
		return newmap;
	}
	
	public static void main(String[] args) {
		System.out.println(new BaseController().success("abc"));
	}
	
	public void keepPara(String key, HttpServletRequest req) {
		req.setAttribute(key, req.getParameter(key));
	}

	public String toJson(Object obj) {
		return JSON.toJSONString(obj);
	}
	
	public String getSql(String key) {
		return SqlUtil.getSql(key);
	}
	
}